package com.wxy.jk.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxy.jk.common.enchance.MpPage;
import com.wxy.jk.common.enchance.MpQueryWrapper;
import com.wxy.jk.common.mapStruct.MapStructs;
import com.wxy.jk.common.util.JsonVos;
import com.wxy.jk.common.util.Uploads;
import com.wxy.jk.mapper.ExamPlaceCourseMapper;
import com.wxy.jk.pojo.po.ExamPlaceCourse;
import com.wxy.jk.pojo.result.CodeMsg;
import com.wxy.jk.pojo.vo.PageVo;
import com.wxy.jk.pojo.vo.list.ExamPlaceCourseVo;
import com.wxy.jk.pojo.vo.req.page.ExamPlaceCoursePageReqVo;
import com.wxy.jk.pojo.vo.req.save.ExamPlaceCourseReqVo;
import com.wxy.jk.service.ExamPlaceCourseService;
import org.springframework.stereotype.Service;

import java.io.Serializable;


@Service
public class ExamPlaceCourseServiceImpl extends ServiceImpl<ExamPlaceCourseMapper, ExamPlaceCourse> implements ExamPlaceCourseService {

    @Override

    public PageVo<ExamPlaceCourseVo> list(ExamPlaceCoursePageReqVo query) {
        MpQueryWrapper<ExamPlaceCourseVo> wrapper = new MpQueryWrapper<>();

        Integer placeId = query.getPlaceId();
        Integer provinceId = query.getProvinceId();
        Integer cityId = query.getCityId();
        Short type = query.getType();
        if (type != null && type >= 0) {
            wrapper.eq("c.type", type);
        }

        // 考场 -> 城市 -> 省份
        if (placeId != null && placeId > 0) {
            wrapper.eq("c.place_id", placeId);
        } else  if (cityId != null && cityId > 0) {
            wrapper.eq("p.city_id", cityId);
        } else if (provinceId != null && provinceId > 0) {
            wrapper.eq("p.province_id", provinceId);
        }

        // 关键词
        wrapper.like(query.getKeyword(), "c.name", "c.intro");
        return baseMapper.selectPageVos(new MpPage<>(query), wrapper).buildVo();
    }

    @Override
    public boolean saveOrUpdate(ExamPlaceCourseReqVo reqVo) {
        try {
            ExamPlaceCourse po = MapStructs.INSTANCE.reqVo2po(reqVo);

            // 上传图片
            String filepath = Uploads.uploadImage(reqVo.getCoverFile());

            // 有新的图片上传成功
            if (filepath != null) {
                // 设置新的封面
                po.setCover(filepath);
            }

            // 保存po
            boolean ret = saveOrUpdate(po);
            if (ret && filepath != null) {
                // 删除旧封面
                Uploads.deleteFile(reqVo.getCover());
            }
            return ret;
        } catch (Exception e) {
            return JsonVos.raise(CodeMsg.UPLOAD_IMG_ERROR);
        }
    }

    @Override
    public boolean removeById(Serializable id) {
        ExamPlaceCourse course = getById(id);
        try {
            if (super.removeById(id)) {
                Uploads.deleteFile(course.getCover());
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
